package com.csxy.six.service.impl;

import com.csxy.six.JwtUtils;
import com.csxy.six.entity.Role;
import com.csxy.six.exception.MyException;
import com.csxy.six.mapper.RoleMapper;
import com.csxy.six.service.PermissionService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public void checkTeacherPermission() {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new MyException(401, "未提供有效的认证信息");
        }

        String token = authHeader.substring(7);

        if (jwtUtils.isTokenExpired(token)) {
            throw new MyException(401, "认证信息已过期");
        }

        // 从令牌获取角色ID
        Long roleId = jwtUtils.getRoleIdFromToken(token);

        // 根据角色ID查询角色信息
        Role role = roleMapper.selectById(roleId);
        if (role == null) {
            throw new MyException(403, "角色信息不存在");
        }

        // 检查是否为教师角色
        if (!"TEACHER".equals(role.getName())) {
            throw new MyException(403, "仅教师账号可访问此功能");
        }
    }
}